package com.example.cinema.bindingdata;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.BindingAdapter;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableField;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.cinema.BR;
import com.example.cinema.GridViewHeight;
import com.example.cinema.R;
import com.example.cinema.UserAttribute;
import com.example.cinema.adapter.Blank2GridAdapter;
import com.example.cinema.adapter.ImagePageAdapter;
import com.example.cinema.drawview.CircleVideoPlayer;
import com.example.cinema.request.RequestData;
import com.example.cinema.request.RequestSend;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class UserItemViewData {
    //头像显示
    @BindingAdapter("useritemurl")
    public static void imageurl(View view, String url){ //自定义View属性映射
        if(view != null)
        {
            RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.defaut_img)
                    .error(R.mipmap.defaut_img)
                    .fallback(R.mipmap.defaut_img);
            Glide.with(view).load(url)
                    .apply(options)
                    .into((ImageView) view);
        }
    }
    //Grid适配器
    @BindingAdapter("gridadapter")
    public static void gridadapter(View view, List<String> url)
    {
        if(url!=null)
        {
            Blank2GridAdapter adapter = new Blank2GridAdapter(url,view.getContext(), R.layout.blank2_grid_item);
            GridView gridView = (GridView) view;
            gridView.setAdapter(adapter);
            new GridViewHeight(gridView,3);
            //点击显示大图
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int h = view.getContext().getResources().getDisplayMetrics().heightPixels;
                    int w = view.getContext().getResources().getDisplayMetrics().widthPixels;

                    Log.i("UUUUSSU",url.get(0));

                    ImagePageAdapter pageAdapter = new ImagePageAdapter(view.getContext(),url, BR.imgpagedata);
                    ViewPager viewPager = new ViewPager(view.getContext());
                    viewPager.setAdapter(pageAdapter);

                    viewPager.setCurrentItem(position);
                    AlertDialog dialog = new AlertDialog.Builder(view.getContext()).create();
                    dialog.setView(viewPager);
                    dialog.show();
                    Window window = dialog.getWindow();
                    window.getDecorView().setBackgroundColor(Color.BLACK);
                    window.getDecorView().setPadding(0,0,0,0);
                    window.setGravity(Gravity.CENTER);
                    WindowManager.LayoutParams params = window.getAttributes();
                    params.height = WindowManager.LayoutParams.WRAP_CONTENT;
                    params.width = w;
                    window.setAttributes(params);
                    if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
                    {
                        view.setSystemUiVisibility(View.GONE);
                    }else if(Build.VERSION.SDK_INT>=19){
                        int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
                        view.setSystemUiVisibility(UIOP);
                    }
                }
            });
        }

    }
    //评论点击
    private List<Blan2ListItemData> data = new ArrayList<>();
    private CircleListAdapter listAdapter;
    private EditText editText;
    private String url;
    public void pinlunclick(View view,String id)
    {
        if(url==null)
        {
            Context context = view.getContext();
            try {
                ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                url = info.metaData.getString("url");
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }




        data.clear();
        UserAttribute attribute = (UserAttribute) view.getContext().getApplicationContext();
        //获取评论数据
        ReqUserAssess(id,1,30,view.getContext());
        //弹出评论框
        View plview = LayoutInflater.from(view.getContext()).inflate(R.layout.circle_dialog_item,null);
        ImageView senimg = plview.findViewById(R.id.send);
        editText= plview.findViewById(R.id.edit_context);
        ListView listView= plview.findViewById(R.id.commentlist);
        ImageView close = plview.findViewById(R.id.close);
        listAdapter = new CircleListAdapter(data,view.getContext(),R.layout.blank2_list_item);
        listView.setAdapter(listAdapter);
        //发送
        senimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("RRR","开始发送");
                if(attribute.getUname()==null)
                {
                    Intent intent = new Intent();
                    intent.setAction("sign");
                    v.getContext().startActivity(intent);
                    return;
                }
                String etext = editText.getText().toString();
                if(etext.length()>1)
                {
                    Log.i("RRR","开始发送1");
                    SendUserAssess(v.getContext(),id,etext,attribute);
                }
            }
        });

        int w = view.getContext().getResources().getDisplayMetrics().widthPixels;
        int h = view.getContext().getResources().getDisplayMetrics().heightPixels;
        AlertDialog dialog = new AlertDialog.Builder(view.getContext())
                .setView(plview)
                .create();
        dialog.show();
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
                {
                    view.setSystemUiVisibility(View.GONE);
                }else if(Build.VERSION.SDK_INT>=19){
                    int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
                    view.setSystemUiVisibility(UIOP);
                }
            }
        });
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setMinimumWidth(w);
        window.getDecorView().setPadding(0,0,0,0);
        window.getDecorView().setBackgroundResource(R.drawable.dialog_round_bag);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = w;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
        //关闭
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();

            }
        });
        if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
        {
            view.setSystemUiVisibility(View.GONE);
        }else if(Build.VERSION.SDK_INT>=19){
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }
    }
    //播放点击
    public void playerclick(View view,String url,String imgurl)
    {
        int w = view.getContext().getResources().getDisplayMetrics().widthPixels;
        int h = view.getContext().getResources().getDisplayMetrics().heightPixels;
        AlertDialog dialog = new AlertDialog.Builder(view.getContext()).create();
        CircleVideoPlayer player = new CircleVideoPlayer(view.getContext());
        player.SetUrlPlayer(url);
        dialog.setView(player);
        dialog.setCancelable(false);
        dialog.show();
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(15,20,15,30);
        window.getDecorView().setBackgroundColor(Color.argb(0,0,0,0));
        WindowManager.LayoutParams wmanager = window.getAttributes();
        wmanager.width = w;
        wmanager.height= h;
        window.setAttributes(wmanager);
        player.Setimageurl(imgurl);
        player.loadVideo();
        player.startplay();
        player.SetOnCloseClickListener(new CircleVideoPlayer.OnClodeClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
                player.stopplay();
            }
        });
    }
    //帖子点赞
    public void pinlunzan(View view,String mid)
    {
        UserAttribute attribute = (UserAttribute) view.getContext().getApplicationContext();
        if(attribute.getToken()==null||attribute.getUID()==null)
        {
            Intent intent = new Intent();
            intent.setAction("sign");
            view.getContext().startActivity(intent);
            return;
        }
        ImageView image = (ImageView) view;
        image.getDrawable().setLevel(2);
        int i = Integer.valueOf(this.evaluate.get());
        this.evaluate.set(String.valueOf(i+1));
        ThredZan(mid,attribute.getUID(),view.getContext(),attribute);
    }


    public ObservableField<String> userimage = new ObservableField<>();//用户头像
    public ObservableField<String> username  = new ObservableField<>();//用户名称
    public ObservableField<String> usertime  = new ObservableField<>();//发布时间
    public ObservableField<String> usertitle = new ObservableField<>();//帖子标题
    public ObservableField<String> usermsg   = new ObservableField<>();//帖子内容
    public ObservableField<String> userid   = new ObservableField<>();//用户ID
    public ObservableField<String> circleid = new ObservableField<>();//帖子ID
    public ObservableField<String> money = new ObservableField<>();//打赏金额
    public ObservableField<List<String>> contenimg = new ObservableField<>();//内容面图
    public ObservableField<String> coverimg = new ObservableField<>();//封面图
    public ObservableField<String> gifpath = new ObservableField<>();//GIF动图播放链接
    public ObservableField<String> evaluate = new ObservableField<>();//评价数量
    public ObservableField<String> admire = new ObservableField<>();//点赞数


    ///提交评价
    private void SendUserAssess(Context context,String id,String etext,UserAttribute attribute) {
        new Thread()
        {
            @Override
            public void run() {
                RequestSend send = new RequestSend(context);
                Log.i("RRR","开始发送1");
                boolean s = send.SendMoodAssess(id,attribute,etext);
                Log.i("RRR","开始发送1"+s);
                if(s)
                {
                    Message message = new Message();
                    message.what = 1001;
                    message.obj = context;
                    handler.sendMessage(message);
                }

            }
        }.start();
    }
    ///获取评价数据
    private void ReqUserAssess(String vid,int p,int l,Context context)
    {
        new Thread()
        {
            @Override
            public void run() {
                RequestData requestData = new RequestData(context);
                JSONArray array  = requestData.getMoodPingJia(p,l,vid);
                try {
                    List<Blan2ListItemData> bdata = new ArrayList<>();
                    for (int i=0;i<array.length();i++)
                    {
                        Blan2ListItemData listItemData = new Blan2ListItemData();

                        JSONObject jsonObject = array.getJSONObject(i);
                        listItemData.image.set(url+jsonObject.getString("userimg"));
                        listItemData.cent.set(jsonObject.getString("sendcentext"));
                        listItemData.name.set(jsonObject.getString("username"));
                        listItemData.usid.set(jsonObject.getString("useruid"));
                        listItemData.vids.set(jsonObject.getString("moodmid"));
                        listItemData.zanb.set(jsonObject.getString("userlove"));
                        listItemData.tid.set(jsonObject.getString("tid"));
                        bdata.add(listItemData);

                    }
                    data.addAll(bdata);
                    handler.sendEmptyMessage(1000);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    //帖子点赞
    private void ThredZan(String mid,String uid,Context context,UserAttribute attribute)
    {
        new Thread()
        {
            @Override
            public void run() {
                RequestSend requestSend = new RequestSend(context);
                boolean s = requestSend.MoodZan(mid,uid,attribute);
                if(s)
                {

                }
            }
        }.start();
    }
    Handler handler = new Handler(Looper.getMainLooper())
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what==1000)
            {
                Log.i("JJJJ","更新");
                listAdapter.notifyDataSetChanged();
                return;
            }
            if(msg.what == 1001)
            {
                Toast.makeText((Context) msg.obj,"评论成功!审核后显示",Toast.LENGTH_LONG).show();
                editText.setText(null);
            }
        }
    };
}
